using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection.Metadata;
using System.Text;
using System.Threading;

namespace CoreConsoleApp1
{
	class Client
	{
		static Socket socket;
		static void Main(string[] args)
		{
			socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

			EndPoint endpoint = new IPEndPoint(IPAddress.Parse("192.168.213.1"), 50000);//目标服务器IP端口号
			socket.Connect(endpoint);

			new Thread(new ParameterizedThreadStart(ReceiveData)).Start(socket);//读线程
			new Thread(new ParameterizedThreadStart(SendMessage)).Start(socket);//写线程
		}

		private static void SendMessage(object obj)
		{
			try
			{
				(obj as Socket).Send(Encoding.Unicode.GetBytes(Console.ReadLine()));
				SendMessage(obj);
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}

		private static void ReceiveData(object obj)
		{
			try
			{
				Socket remote = obj as Socket;
				byte[] buffer = new byte[1024];
				int length = remote.Receive(buffer);
				if (!remote.Connected || length == 0)//我也不知道为什么服务器把我干掉，或者服务器关掉的时候，这边会不停地收到空串
				{
					Console.WriteLine("------服务器断开连接------");
					return;
				}

				string msg = Encoding.Unicode.GetString(buffer, 0, length);
				Console.WriteLine(msg);

				ReceiveData(obj);
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
			}
			
		}
	}
}
